use std::fs;
use std::env;
use std::path::Path;

/// Converts all CRLF line endings (\r\n) to LF (\n) in the specified directory
pub fn normalize_line_endings<P: AsRef<Path>>(dir: P) -> Result<(), Box<dyn std::error::Error>> {
    let dir = dir.as_ref();
    if !dir.is_dir() {
        return Err(Box::new(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Not a directory")));
    }

    let walk_dir = fs::read_dir(dir).map_err(|e| Box::new(e))?;

    for entry in walk_dir {
        let entry = entry.map_err(|e| Box::new(e))?;
        let path = entry.path();

        if path.is_file() {
            // Read the file content
            let content = fs::read_to_string(&path)
                .map_err(|e| Box::new(e))?;

            // Replace CRLF with LF
            let normalized = content.replace("\r\n", "\n");

            // Write back to the file
            fs::write(&path, normalized)
                .map_err(|e| Box::new(e))?;
        } else if path.is_dir() {
            // Recursively process subdirectories
            normalize_line_endings(&path)?;
        }
    }

    Ok(())
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let dir = args.get(1).expect("Usage: crlf2lf <directory>");
    normalize_line_endings(dir).unwrap();
}
